<template>
  <div class="table_content">
    <el-card>
      <div style="text-align: right; margin-bottom: 20px;display: flex;justify-content: right;">
        <div style="width:200px;margin-right:10px;">
          <el-input v-model="roleNameLike" placeholder="请输入内容" />
        </div>
        <el-button type="primary" size="small" @click="getRoleList('1')">查询</el-button>
        <el-button type="primary" size="small" @click="getRoleList('0')">重置</el-button>
        <el-button type="primary" size="small" @click="addMenu">添加角色</el-button>
      </div>
      <div class="table">
        <el-table :data="roleData" size="small" :height="tbHeight" :header-cell-style="{background:'#FAFAFA'}"
          :row-style="{height:'58px'}">
          <el-table-column prop="name" label="角色名称" align="center" />
          <el-table-column prop="roleDesc" label="角色类型" align="center" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <span class="msg77" @click="distribute(scope.row)">分配权限</span>
              <span class="msg99" @click="editCarbon(scope.row)">编辑</span>
              <span class="msg88" @click="delCarbon(scope.row)">删除</span>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- <div class="pagination">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageIndex"
            :page-sizes="pageSizes" :page-size="pageSize" layout="total, sizes, prev, pager, next" :total="total">
          </el-pagination>
        </div> -->
      </div>
    </el-card>
    <!-- 弹框 -->
    <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
      <el-form ref="formName" v-loading="loading" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色类型">
          <el-input v-model="formData.roleDesc" placeholder="请输入角色类型" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="clickSubmit">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配权限给角色的弹框 -->
    <el-dialog v-loading="treeLoading" title="分配权限" :visible="showAssignDialog" @open="openAssignDialog"
      @close="closeAssginDialog">
      <!-- this.$refs.tree.getCheckedKeys() 获取选中的所有项 -->
      <!-- this.$refs.tree.setCheckedKeys([3, 5, 7]) 设置选中的项 -->
      <!-- <el-tree ref="tree" :data="assignList" :default-expand-all="true" :show-checkbox="true" :check-strictly="true"
        node-key="id" :default-checked-keys="checkArr" /> -->
      <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;" />
      <el-checkbox-group v-model="checkedCities" class="my_checkbox" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="item in cities" :key="item.uniqueName" :label="item.uniqueName">{{ item.name }}
        </el-checkbox>
      </el-checkbox-group>

      <template #footer>
        <div style="text-align: right">
          <el-button @click="closeAssginDialog">取消</el-button>
          <el-button type="primary" @click="clickSubmitAssign">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 由数字、26个英文字母或者下划线组成的字符串
export default {
  name: 'Menu2',
  data() {
    return {
      roleData: [],
      tbHeight: 540,
      showTitle: '',
      showDialog: false,
      loading: false,
      formData: {
        name: '',
        roleDesc: ''
      },
      pageIndex: 1, // 当前多少页
      pageSizes: [10, 30, 50, 100], // 显示多少条
      total: 0, // 总条数
      pageSize: 10, // 每页多少条
      Update: false, // 判断发送编辑接口/新增接口
      showAssignDialog: false, // 控制弹框的显示隐藏
      treeLoading: false, // 权限弹框 加载
      roleNameLike: '',
      role: {}, // 点击分配权限获取到角色

      checkAll: false, // 全选的状态
      checkedCities: [], // 选中的值
      cities: [], // 多选框的数据
      isIndeterminate: true, // 分配菜单，全选按钮
      // 校验
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur'] },
          { max: 100, message: '角色名称长度最大100', trigger: ['blur'] }
        ],
        roleDesc: [
          { required: true, message: '请输入角色类型', trigger: ['blur'] },
          { max: 10, message: '角色类型长度最大100', trigger: ['blur'] }
        ]
      },
      cityOptions: [] // 用于多选框全选
      // assignList: [], // 树形结构数据
      // checkArr: [] // 树形结构选中的值

    }
  },
  created() {
    const that = this
    // let ctHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
    // that.tbHeight = ctHeight - 310
    that.rbacRoleQuery()
  },
  methods: {
    // 分配按钮
    distribute(role) {
      const that = this
      that.showAssignDialog = true
      that.role = role
    },
    // 点击确认, 进行提交分配
    async clickSubmitAssign() {
      const that = this
      that.rbacRoleAddRoleMenu()
    },
    // 权限弹框取消
    closeAssginDialog() {
      const that = this
      that.showAssignDialog = false
      that.checkArr = []
      that.role = {}
      // this.$refs.tree.setCheckedKeys([]) // 关闭时, 重置选中状态
    },
    // 弹框显示时, 触发的函数, 可以发送请求, 获取树形结构的数据
    async openAssignDialog() {
      const that = this
      this.treeLoading = true
      // 查询全部菜单
      that.$store.dispatch('menu/rbacMenuQueryAll').then(res => {
        // console.log(res, '获取到的路由')
        if (res.data) {
          that.cities = res.data
          // 用户全选
          res.data.map(item => {
            that.cityOptions.push(item.uniqueName)
          })
          // 根据角色(id)查询关联菜单
          that.rbacRoleQueryMenuByRole()
        }
      })
      this.treeLoading = false
    },

    // 显示已绑定的
    // async getCheckedPoint () {
    //   const that = this
    //   const arr = []
    //   pointCheckedList = await that.getMenuBtnList(that.assignList, arr) // 递归查询

    // },
    // getMenuBtnList (siteTreeData, checkList) {
    //   const that = this
    //   for (const item of siteTreeData) {
    //     if (item.selected) {
    //       checkList.push(item)
    //     } else if (item.children && item.children.length > 0) {
    //       that.getMenuBtnList(item.children, checkList)
    //     }
    //   }
    //   return checkList
    // },
    // 添加角色按钮
    addMenu() {
      const that = this
      that.showDialog = true
      that.showTitle = '新增角色'
    },
    // 删除按钮
    delCarbon(row) {
      const that = this
      that.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.rbacRoleDelete(row.id)
      }).catch(() => { })
    },
    // 编辑按钮
    editCarbon(row) {
      const that = this
      // console.log(row, '编辑按钮')
      that.showTitle = '编辑角色'
      that.showDialog = true
      that.Update = true
      that.formData = {
        ...row
      }
    },
    // 删除角色 接口
    rbacRoleDelete(id) {
      const that = this
      const data = {
        id
      }
      that.$store.dispatch('role/rbacRoleDelete', data).then(res => {
        // console.log(res, '删除角色')
        if (res.data) {
          that.rbacRoleQuery() // 获取角色
          that.$message.success('删除成功')
        }
      })
    },
    // 更新角色(编辑) 接口
    rbacRoleUpdate() {
      const that = this
      const data = that.formData
      that.$store.dispatch('role/rbacRoleUpdate', data).then(res => {
        // console.log(res, '编辑')
        if (res) {
          that.showDialog = false
          that.rbacRoleQuery() // 获取角色
          that.$message.success('编辑成功')
        }
      })
    },
    // 查询全部角色接口
    rbacRoleQuery() {
      const that = this
      const data = {
        roleNameLike: that.roleNameLike
      }
      that.$store.dispatch('role/rbacRoleQuery', data).then(res => {
        // console.log(res, '查询全部角色')
        if (res.data) {
          that.roleData = res.data
        }
      })
    },
    // 查询/重置按钮
    getRoleList(type) {
      const that = this
      if (type === '1') {
        that.rbacRoleQuery()
      } else {
        that.roleNameLike = ''
        that.rbacRoleQuery()
      }
    },
    // 新增角色接口
    rbacRoleAdd() {
      const that = this
      const data = that.formData
      that.$store.dispatch('role/rbacRoleAdd', data).then(res => {
        // console.log(res, '新增菜单')
        if (res.data) {
          that.showDialog = false
          that.formData = {
            name: '',
            roleDesc: ''
          }
          that.$message.success('新增成功')
          that.rbacRoleQuery() // 获取所有角色
        }
      })
    },
    // 绑定角色(id)和菜单(id)之间的关系【包括新增更新】
    rbacRoleAddRoleMenu() {
      const that = this
      const functionList = []
      that.checkedCities.forEach(item => {
        functionList.push({
          uniqueName: item
        })
      })
      const data = {
        role: {
          id: that.role.id
        },
        functionList: functionList
      }

      that.$store.dispatch('role/rbacRoleAddRoleMenu', data).then(res => {
        // console.log(res, '绑定角色(id)和菜单(id)之间的关系【包括新增更新】')
        if (res.data) {
          that.$message.success('分配成功')
          that.showAssignDialog = false
        }
      })
    },
    // 根据角色(id)查询关联菜单
    rbacRoleQueryMenuByRole() {
      const that = this
      const data = that.role
      that.$store.dispatch('role/rbacRoleQueryMenuByRole', data).then(res => {
        // console.log(res, '根据角色(id)查询关联菜单')
        if (res.data) {
          that.checkedCities = []
          res.data.forEach(item => {
            that.checkedCities.push(item.uniqueName)
          })
        }
      })
    },
    // 弹框确认
    clickSubmit() {
      const that = this
      this.$refs.formName.validate((valid) => {
        if (valid) {
          if (that.Update) {
            that.rbacRoleUpdate() // 编辑
          } else {
            that.rbacRoleAdd() // 新增
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 弹框取消
    closeDialog() {
      const that = this
      that.showDialog = false
      that.Update = false
      that.formData = {
        name: '',
        roleDesc: ''
      }
    },
    // 每页多少条
    handleSizeChange(val) {
      this.pageSize = val
      this.searchReport()
    },
    // 当前页
    handleCurrentChange(val) {
      this.pageIndex = val
      this.searchReport()
    },

    // 分配菜单，全选发生变化时触发
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cityOptions : []
      this.isIndeterminate = false
    },
    // 分配菜单，某项发生变化是触发
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.cities.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length
    }

  }

}
</script>

<style lang="scss" scoped>
::v-deep .el-card__body {
  padding: 20px;
}
::v-deep .el-dialog__header_xqh {
  padding: 20px 20px 10px;
  background: #66b1ff;
  .el-dialog__title {
    color: #fff;
  }
}
.table_content {
  margin-top: 20px;
  width: 100%;
  background-color: #fff;
  border-radius: 4px;
  padding: 0 20px 20px 20px;
}
.table {
  overflow: auto;
  height: vhPt(1600);
  box-sizing: border-box;
  .empty {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    .img_w_h {
      width: 56px;
      height: 56px;
    }
  }
  .pagination {
    display: flex;
    justify-content: right;
    margin-top: 30px;
  }
}
.my_checkbox {
  .el-checkbox {
    width: 140px;
  }
}
</style>
